package org.gruposp2p.proyectokarma.service

import org.gruposp2p.proyectokarma.domain.Peer;
import org.gruposp2p.proyectokarma.domain.PeerRole;
import org.gruposp2p.proyectokarma.domain.Role;
import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.Vote;
import org.gruposp2p.proyectokarma.domain.RegistrationCode;
import org.springframework.transaction.annotation.*
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class PeerService {
	
	static transactional = false

	//TODO transaction 
	def verifyRegistration(RegistrationCode registrationCode, Peer user) {
		user.accountLocked = false
		user.save()
		for (roleName in ConfigurationHolder.config.register.defaultRoleNames) {
			def role =  Role.findByAuthority(roleName)
			PeerRole.create(user,role, true)
		}
		registrationCode.delete(flush:true)
		return user
	}


	
    String insertData () {
        for (int i=0; i<20; i++) {
            def username = 'Peer' + i
            def peerid = 'Peerid' + i
            def	enabled = true
            def email = username + '@spain.es'
            def dateOfBird = new Date();
            def peer = new Peer(username: username, enabled: enabled, email:email,
                dateOfBird:dateOfBird, authority:"ROLE_USER", dateAdded:dateOfBird,
                name:username, peerid:peerid)
            private Set documents = new HashSet(0);
            for (int j=0; j<2; j++) {
                    String name = 'Nombre del documento: \'' + i + j + '\'';
                    String content = 'Contenido del documento ' + i + j;
                    def document = new Document (name:name, content:content);
                    document.setPeer(peer);
                    documents.add(document);
            }
            peer.setDocuments(documents);
            peer.save(flush: true)
        }

        /*def peers = Peer.list().each({it.documents.each {
                for (Peer peer : Peer.list()) {
                    def voteValue = 'elección del usuario: ' + peer.getUserid() + ' correspondiente a la opción: ' + it.getName()
                        Vote vote = new Vote(value:voteValue);
                        peer.addToVotes(vote)
                        it.addToVotes(vote)
                }
        }});*/
        return "20 Peers Inserted"
    }

}

